package com.vnaloha.dbunit;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.dbunit.DatabaseUnitException;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.DatabaseSequenceFilter;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.FilteredDataSet;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.filter.ITableFilter;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.ext.mysql.MySqlDataTypeFactory;

public class CreateDatasetDBUnit {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 * @throws ClassNotFoundException 
	 * @throws SQLException 
	 * @throws DatabaseUnitException 
	 */
	public static void main(String[] args) throws Exception {

		final Map<String, Object> DB_UNIT_CLB_PROPERTIES = new HashMap<String, Object>();
		DB_UNIT_CLB_PROPERTIES.put(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new MySqlDataTypeFactory());
		DB_UNIT_CLB_PROPERTIES.put("http://www.dbunit.org/features/caseSensitiveTableNames", true);
		DB_UNIT_CLB_PROPERTIES.put("http://www.dbunit.org/features/qualifiedTableNames", true);
		DB_UNIT_CLB_PROPERTIES.put("http://www.dbunit.org/features/batchedStatements", true);
		DB_UNIT_CLB_PROPERTIES.put(DatabaseConfig.PROPERTY_ESCAPE_PATTERN, "\"?\"");
		// database connection
		Class driverClass = Class.forName("com.mysql.jdbc.Driver");
		
		String mysqlDatabase = "jdbc:mysql://192.168.1.11:3306/JioHealth2?zeroDateTimeBehavior=convertToNull&characterEncoding=UTF-8&useUnicode=true&autoReconnect=true";
		
		Connection jdbcConnection = DriverManager.getConnection(mysqlDatabase,"root", "root");
		
		IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);
		for (Map.Entry<String, Object> prop : DB_UNIT_CLB_PROPERTIES.entrySet()) {
			connection.getConfig().setProperty(prop.getKey(), prop.getValue());
		}
		// full database export, automatically order tables by foreign key
		// constraints
		ITableFilter filter = new DatabaseSequenceFilter(connection);
		IDataSet fullDataSet = new FilteredDataSet(filter, connection.createDataSet());
		FlatXmlDataSet.write(fullDataSet, new FileOutputStream("/data/temp/datatest/fulldataset.xml"));
		
//        String [] tables = connection.createDataSet().getTableNames();
//        
//        for(String o:tables){
//        	// partial database export
//            QueryDataSet partialDataSet = new QueryDataSet(connection);
//        	partialDataSet.addTable(o);
//        	FlatXmlDataSet.write(partialDataSet, new FileOutputStream("/data/temp/datatest/" + o + ".xml"));
//        }
	}

}
